package org.java.library;

import java.io.*;

/**
 * 测试java的序列化和反序列化
 * Created by Dwyane-Wevil on 2017/3/4.
 */
public class SerializableTest {

    public static void main(String[] args)
    {
        // 测试序列化
        //serializable();
        // 测试反序列化
        serializableDesc();
    }

    /**
     * 对象序列化：将Student保存到本地student.txt里
     * */
    public static void serializable(){
        // 创建Student对象和本地文件
        Student st = new Student("Tom",'M',20,3.6);
        File file = new File("D:\\tmp\\student.txt");
        try
        {
            file.createNewFile();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

        try
        {
            //Student对象序列化过程
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(st);
            oos.flush();
            oos.close();
            fos.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 测试反序列化：将本地student.txt的Student对象读取出来
     * */
    public static void serializableDesc(){
        try {
            //Student对象反序列化过程
            FileInputStream fis = new FileInputStream(new File("D:\\tmp\\student.txt"));
            ObjectInputStream ois = new ObjectInputStream(fis);
            Student st1 = (Student) ois.readObject();
            System.out.println("name = " + st1.getName());
            System.out.println("sex = " + st1.getSex());
            System.out.println("year = " + st1.getYear());
            System.out.println("gpa = " + st1.getGpa());
            ois.close();
            fis.close();
        }catch(ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
